package com.xiaoying.server.publish.impl;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

import org.apache.commons.configuration.Configuration;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Component;

import com.xiaoying.server.publish.Handler;
import com.xiaoying.server.publish.entity.FileInfo;
import com.xiaoying.server.publish.entity.UploadResult;
import com.xiaoying.server.publish.task.UploadDealTask;
import com.xiaoying.server.publish.upload.UploadFile;
import com.xiaoying.server.publish.upload.UploadFileManager;

public class RequestHandler implements Handler,Runnable{
	private static Log log = LogFactory.getFactory().getInstance(RequestHandler.class);
	
	private int maxThread=10;
    private BlockingQueue<FileInfo> requestQueue;
    private BlockingQueue<UploadResult> responseQueue;
    private Executor executor = null;
    private UploadFileManager uploadFileManager=null;
    
    @Override
    public void handle(BlockingQueue<FileInfo> reqQ,
            BlockingQueue<UploadResult> resQ) {
        this.requestQueue = reqQ;
        this.responseQueue = resQ;
        Thread proc = new Thread(this);
        proc.start();
    }

    @Override
    public void init(Configuration config) throws Exception {
        maxThread = config.getInt("RequestHandler.maxThread", 10);
        executor = Executors.newFixedThreadPool(maxThread);
        uploadFileManager = UploadFileManager.getInstance();
        uploadFileManager.init();
        Executors.newSingleThreadExecutor().execute(uploadFileManager);
    }

	@Override
    public void run() {
        while (true) {
            FileInfo fileInfo = null;  
            try {
				fileInfo = requestQueue.take();
                if (log.isDebugEnabled())
                    log.debug("RequestHandler requestQueue():"+requestQueue.size()); 
                UploadFile uploadFile = new UploadFile(requestQueue,responseQueue);
                UploadDealTask task = new UploadDealTask(requestQueue, responseQueue,uploadFile,fileInfo);
                executor.execute(task);
			} catch (InterruptedException e) {
                if (fileInfo != null) {
                	requestQueue.add(fileInfo);
                }
			}            
        }
    }

//	public int getMaxThread() {
//		return maxThread;
//	}
//
//	public void setMaxThread(int maxThread) {
//		this.maxThread = maxThread;
//	}
	
	
}
